//
//  WillReleasedViewController.m
//  MyMovie
//
//  Created by lanou3g on 15/9/17.
//  Copyright (c) 2015年 HeQiangQiang. All rights reserved.
//

#import "WillReleasedViewController.h"
#import "PlayerDataBase.h"

@interface WillReleasedViewController ()<UISearchBarDelegate>

@property (nonatomic, strong) NSMutableArray *saveArray;//收藏数组
@property (nonatomic, strong) UISearchBar *search;
@property (nonatomic, strong) UIButton *leftButton;

@end

@implementation WillReleasedViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    if (self.count == 1) {
        self.willReleasedArr = [NSMutableArray arrayWithArray:[[PlayerDataBase shareDataBase] selectFromTable:@"MyMovie"]];
        UIBarButtonItem *leftBar = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:(UIBarButtonItemStylePlain) target:self action:@selector(jump)];
        self.navigationItem.leftBarButtonItem = leftBar;
        self.navigationItem.title = @"私人收藏";
    }else {
        UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"42"] style:(UIBarButtonItemStylePlain) target:self action:@selector(button)];
        self.navigationItem.rightBarButtonItem = button;
        [SVProgressHUD show];
        // Json解析将要上映的电影
        [self setWillReleasedMovieWithJson];
    }
    
    // 设置tableView
    [self setTableView];
    [self setUp];
}
- (void)jump {
    [self dismissViewControllerAnimated:YES completion:nil];
}
//搜索
- (void)setUp {
    self.search = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 20, kWidth, 44)];
    self.search.placeholder = @"电影名";
    [self.search setShowsCancelButton:YES animated:YES];
    self.search.hidden = YES;
    self.search.delegate = self;
    [self.navigationController.view addSubview:self.search];
}
- (void)button {
    self.search.hidden = NO;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self.search resignFirstResponder];
    self.search.hidden = YES;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    self.navigationItem.title = @"搜索结果";
    self.leftButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    self.leftButton.frame = CGRectMake(10, 20, 40, 40);
    self.leftButton.hidden = NO;
    [self.leftButton addTarget:self action:@selector(setWillReleasedMovieWithJson) forControlEvents:(UIControlEventTouchUpInside)];
    [self.leftButton setTitle:@"返回" forState:(UIControlStateNormal)];
    [self.navigationController.view addSubview:self.leftButton];
    
    [self.willReleasedArr removeAllObjects];
    NSString *string = [kSearchUrl stringByReplacingOccurrencesOfString:@"电影名" withString:[searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    [LORequestManger GET:string success:^(id response) {
        NSDictionary *dictionary = (NSDictionary *)response;
        NSArray *entriesArr = dictionary[@"subjects"];
        for (NSDictionary *dic in entriesArr) {
            WillReleasedModel *model = [WillReleasedModel setJsonWithDictionary:dic];
            [self.willReleasedArr addObject:model];
        }
        [self.tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}
// Json解析 将要上映的电影
- (void)setWillReleasedMovieWithJson {
    self.leftButton.hidden = YES;
    self.navigationItem.title = @"即将上映";
    [self.willReleasedArr removeAllObjects];
    [LORequestManger GET:kWillReleasedMovieUrl success:^(id response) {
        NSDictionary *dictionary = (NSDictionary *)response;
        NSArray *entriesArr = dictionary[@"entries"];
        for (NSDictionary *dic in entriesArr) {
            WillReleasedModel *model = [WillReleasedModel setJsonWithDictionary:dic];
            [self.willReleasedArr addObject:model];
        }
        [self.tableView reloadData];
        [SVProgressHUD dismiss];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}

// 懒加载
- (NSMutableArray *)willReleasedArr {
    if (!_willReleasedArr) {
        _willReleasedArr = [[NSMutableArray alloc] init];
    }
    return _willReleasedArr;
}
- (NSMutableArray *)saveArray {
    if (!_saveArray) {
        _saveArray = [NSMutableArray array];
    }
    return _saveArray;
}
// 设置tableView
- (void)setTableView {
    self.tableView = [[UITableView alloc] initWithFrame:kBounds style:(UITableViewStylePlain)];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor= [UIColor clearColor];
    [self.view addSubview:self.tableView];
    UIVisualEffectView *backVisual = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
    backVisual.frame = self.tableView.bounds;
    backVisual.alpha = 1.0;
    self.tableView.backgroundView = backVisual;
}


#pragma mark----------tableView的代理方法---------

// 返回分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

// 返回行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.willReleasedArr.count;
}

// 返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"WillReleasedCell";
    WillReleasedTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[WillReleasedTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
    }
    cell.collectionButton.selected = NO;
    cell.collectionButton.tag = indexPath.row + 10000;
    WillReleasedModel *model = self.willReleasedArr[indexPath.row];
    
    NSString *largImage = model.images[@"large"];
    NSMutableArray *array = [NSMutableArray arrayWithArray:[[PlayerDataBase shareDataBase] selectFromTable:@"MyMovie"]];
    for (WillReleasedModel *willMoel in array) {
        if ([model.title isEqualToString:willMoel.title]) {
            cell.collectionButton.selected = YES;
        [cell setViewWithImageName:largImage title:willMoel.title movieOriginalName:willMoel.original_title pubDate:willMoel.pubdate collection:willMoel.collection];
        }
    }
    if (self.count !=1) {
        
        [cell setViewWithImageName:largImage title:model.title movieOriginalName:model.original_title pubDate:model.pubdate collection:model.collection];
    }
    [cell setButtonClickWithTarget:self action:@selector(collectionButtonCilck:)];
    return cell;
}

// 收藏按钮的点击事件
- (void)collectionButtonCilck:(UIButton *)button {
    button.selected = !button.selected;
    
    WillReleasedModel *model = self.willReleasedArr[button.tag - 10000];
    if (button.selected) {
        [[PlayerDataBase shareDataBase] insertIntoTable:@"MyMovie" Model:model];//(需要导入libsqlite3.dylib)
    } else {
        [[PlayerDataBase shareDataBase] deleteModelFromTable:@"MyMovie" WithSongID:model.ID];
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 125 * kFitHeight;
}

// cell点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.search.hidden = YES;
    self.leftButton.hidden = YES;
    //创建CATransition对象
    CATransition *animation = [CATransition animation];
    //设置运动时间
    animation.duration = 1.0;
    animation.delegate = self;
    //设置运动type
    animation.type = @"pageCurl";
    //设置子类
    animation.subtype = kCATransitionFromBottom;
    //设置运动速度
    animation.timingFunction = UIViewAnimationOptionCurveEaseInOut;
    [self.navigationController.view.layer addAnimation:animation forKey:@"b"];
    
    WillReleasedModel *model = self.willReleasedArr[indexPath.row];
    NSLog(@"%@",model.ID);
    DetailMovieViewController *detailVC = [[DetailMovieViewController alloc] init];
//    detailVC.movieID = model.ID;
    detailVC.willModel = model;
    [self.navigationController pushViewController:detailVC animated:YES];
}
//每次加载都刷新
- (void)viewWillAppear:(BOOL)animated {
    [self.tableView reloadData];
    self.leftButton.hidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
